import { Component, OnInit } from '@angular/core';
import { EChartOption } from 'echarts';
import * as moment from 'moment';
import { DataManagementService } from '../data-management.services';
import { NotificationService } from 'app/shared/service';
import { PublicService } from 'app/public/public.service';
import { MESSAGE_CHANNEL, SELECT_OPTIONS } from 'app/app.constants';
import { differenceInCalendarDays } from 'date-fns';
import { BullySubjectService } from 'app/shared/service';

@Component({
    selector: 'itmp-intersection-traffic-volume-report',
    templateUrl: './intersection-traffic-volume-report.component.html',
    styleUrls: ['./intersection-traffic-volume-report.component.css']
})
export class IntersectionTrafficVolumeReportComponent implements OnInit {
    startTime = null;
    endTime = null;
    startTimeRange = '';
    endTimeRange = '';
    dateRange = null;
    roadSelect = null;
    roadOptions = [];
    includeSelect = '';
    includeOptions = [];
    intervalSelect = null;
    intervalOptions = [];
    siteSelect = null;
    siteOptions = [];
    queryStartTime = null;
    queryEndTime = null;
    renderHeader = null; // 表头数据的数组
    listOfData = []; // 列表数据的数组
    pagination = null;
    timeRange = [];
    SITE_ID = [];
    interval_zone = [];
    isTableShow = false;
    updateOptions: any;
    sum = '';
    options: EChartOption;
    echartsIntance: any;

    constructor(
        private DMService: DataManagementService,
        private message: NotificationService,
        private publicService: PublicService,
        private bully: BullySubjectService
    ) {}

    ngOnInit() {
        this.getRoad();
        this.intervalOptions = [{ name: '15min', id: 1 }, { name: '30min', id: 2 }, { name: '60min', id: 3 }];
        this.includeOptions = [
            { name: 'Weekday', id: '1%7C2%7C3%7C4%7C5' },
            { name: 'Weekend', id: '6%7C7' },
            { name: 'All', id: '1%7C2%7C3%7C4%7C5%7C6%7C7' }
        ];
    }

    onChartInit(ec: any) {
        this.echartsIntance = ec;
    }

    // 获取road下拉框数据
    getRoad() {
        const response = this.publicService.getSelectOptionsList(SELECT_OPTIONS.TSC_SITE);
        const res = response.data;
        if (res) {
            // this.DetectorDictionary = [...res];
            // this.roadOptions = data;
            this.siteOptions = res;
            this.siteSelect = res[0];
            if (localStorage.getItem('itmp_lang') === 'vi') {
                this.siteOptions.forEach(site => {
                    site.displayName = site.vietName;
                });
            } else {
                this.siteOptions.forEach(site => {
                    site.displayName = site.name;
                });
            }
            this.changeLang();
            this.siteSearch(res[0]);
            // this.roadSelect = data[0].name;
            this.getData();
        }
    }

    changeLang() {
        this.bully.registerBroadcastReceive(MESSAGE_CHANNEL.LANGUAGE_CHANNEL).subscribe(res => {
            if (res.data === 'vi') {
                this.siteOptions.forEach(site => {
                    site.displayName = site.vietName;
                });
                this.siteSelect = this.siteOptions[0];
            } else {
                this.siteOptions.forEach(site => {
                    site.displayName = site.name;
                });
                this.siteSelect = this.siteOptions[0];
            }
        });
    }

    getData() {
        // 获取当天日期
        const day1 = new Date();
        day1.setTime(day1.getTime());
        const thisDay = day1.getFullYear() + '-' + (day1.getMonth() + 1) + '-' + day1.getDate();
        // 获取明天日期
        const day3 = new Date();
        day3.setTime(day3.getTime() + 24 * 60 * 60 * 1000);
        const nextDay = day3.getFullYear() + '-' + (day3.getMonth() + 1) + '-' + day3.getDate();
        const hour = day1.getHours(); // 得到小时
        const minu = day1.getMinutes(); // 得到分钟
        const second = day1.getSeconds();
        const start = new Date(new Date(new Date().toLocaleDateString()).getTime()); // 获取当日的00:00
        const todayStart = thisDay + ` 00:00:00`;
        const todayEnd = thisDay + ` ${hour}:${minu}:${second}`;
        this.dateRange = [todayStart, todayEnd];
        this.startTime = start;
        this.endTime = new Date();
        this.includeSelect = '1%7C2%7C3%7C4%7C5%7C6%7C7';
        this.intervalSelect = '60min';
        this.startTimeRange = '00:00:00';
        this.endTimeRange = `${hour}:${minu}:${second}`;
        this.queryStartTime = thisDay;
        this.queryEndTime = thisDay;
        if (this.roadSelect instanceof Array) {
            const road = [];
            this.sum = '';
            this.roadSelect.forEach(ele => {
                road.push(ele.name.split('<')[0]);
            });
            road.forEach((value, i) => {
                // 将数组每一项加上单引号
                road[i] = "'" + road[i] + "'";
                this.sum += road[i];
                if (i < road.length - 1) {
                    // 每一项中间以|隔开
                    this.sum += '%7C';
                }
            });
        } else if (this.roadSelect) {
            this.sum = "'" + this.roadSelect.name.split('<')[0] + "'";
        }
        // 默认请求当前日期00:00到此刻的数据，间隔60min
        // tslint:disable-next-line: max-line-length
        const queryData = `startDateRange=${thisDay},endDateRange=${thisDay},weekday=1%7C2%7C3%7C4%7C5%7C6%7C7,startTimeRange=00:00:00,endTimeRange=${hour}:${minu}:${second},interval=60min,detectorIds=${
            this.sum
        }`;
        this.DMService.getVolumeRep(queryData).subscribe(res => {
            if (res.messagecode === '000000') {
                const timeRange = `00:00:00~${hour}:${minu}:${second}`;
                this.updateEcharts(res, timeRange);
            }
        });
    }

    search() {
        // tslint:disable-next-line:max-line-length
        if (
            this.queryStartTime === null ||
            this.queryEndTime === null ||
            this.startTimeRange === null ||
            this.endTimeRange === null ||
            this.intervalSelect === null
        ) {
            this.message.notify({ type: 'warning', path: 'DataManagement.TrafficDataReport.select_notify' });
        } else {
            // const sum = '';
            if (this.roadSelect instanceof Array) {
                const road = [];
                this.sum = '';
                this.roadSelect.forEach(ele => {
                    road.push(ele.name.split('<')[0]);
                });
                road.forEach((value, i) => {
                    // 将数组每一项加上单引号
                    road[i] = "'" + road[i] + "'";
                    this.sum += road[i];
                    if (i < road.length - 1) {
                        // 每一项中间以|隔开
                        this.sum += '%7C';
                    }
                });
            } else if (this.roadSelect) {
                this.sum = "'" + this.roadSelect.name.split('<')[0] + "'";
            }
            const a = `startDateRange=${this.queryStartTime},endDateRange=${this.queryEndTime},weekday=${this.includeSelect}`;
            const b = `startTimeRange=${this.startTimeRange},endTimeRange=${this.endTimeRange},interval=${
                this.intervalSelect
            },detectorIds=${this.sum}`;
            const queryData = `${a},${b}`;
            // 获取报表数据
            this.DMService.getVolumeRep(queryData).subscribe(res => {
                if (res.messagecode === '000000') {
                    const timeRange = `${this.startTimeRange}~${this.endTimeRange}`;
                    this.updateEcharts(res, timeRange);
                }
            });
        }
    }

    updateEcharts(res, timeRange) {
        const timeInterval = this.intervalSelect.split('m')[0];
        const resultData = this.DMService.generateAllData(timeInterval, res.data, timeRange, 'DETECTOR_ID');
        const xAxisD = [];
        const detectorTypeMap = {};
        const series = [];
        for (const item of resultData) {
            // 先循环出detetor的个数
            if (!xAxisD.includes(item.interval_zone)) {
                xAxisD.push(item.interval_zone);
            }
            const list = detectorTypeMap[item.DETECTOR_ID];
            if (list) {
                list.data.push(item.AVG_VOLUME);
            } else {
                detectorTypeMap[item.DETECTOR_ID] = {
                    name: `Detector ${item.DETECTOR_ID}`,
                    type: 'line',
                    data: [item.AVG_VOLUME]
                };
                series.push(detectorTypeMap[item.DETECTOR_ID]);
            }
        }
        if (resultData.length === 0) {
            this.message.notify({ type: 'warning', path: 'DataManagement.TrafficDataReport.nodata' });
            this.isTableShow = false;
        } else {
            this.isTableShow = true;
        }
        this.setOption(series, xAxisD);
    }

    setOption(series, xAxisD) {
        this.options = {
            tooltip: {
                trigger: 'axis'
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: [
                {
                    type: 'category',
                    boundaryGap: false,
                    data: xAxisD,
                    axisLabel: {
                        show: true,
                        textStyle: {
                            //x轴座标文字颜色
                            color: '#fff'
                        }
                    }
                }
            ],
            yAxis: {
                type: 'value',
                axisLabel: {
                    show: true,
                    textStyle: {
                        //x轴座标文字颜色
                        color: '#fff'
                    }
                }
            },
            series,
            dataZoom: [
                {
                    type: 'slider',
                    show: false,
                    // start: 0,
                    // end: 50,
                    handleSize: 8
                },
                {
                    type: 'inside'
                    // start: 0,
                    // end: 50
                }
            ]
        };
    }

    // 分页控件改变事件
    onPageChange(e) {
        this.pagination.currentPage = e;
        this.getData();
    }

    onSizeChange(e) {
        this.pagination.pageSize = e;
        this.getData();
    }

    onOk(result: Date): void {}

    onChange(result: Date): void {
        const t1 = moment(result[0]).format('YYYY-MM-DD 00:00:00');
        const t2 = moment(result[1]).format('YYYY-MM-DD 23:59:59');
        this.queryStartTime = t1.split(' ')[0];
        this.queryEndTime = t2.split(' ')[0];
        this.startTimeRange = t1.split(' ')[1];
        this.endTimeRange = t2.split(' ')[1];
    }

    // public startTimeSearch() {
    //     const a = new Date(this.startTime).getTime();
    //     const startTimeRange = moment(a).format('HH:mm');
    //     this.startTimeRange = startTimeRange;
    // }
    // public endTimeSearch() {
    //     const a = new Date(this.endTime).getTime();
    //     const endTimeRange = moment(a).format('HH:mm');
    //     this.endTimeRange = endTimeRange;
    // }
    public roadSearch() {}

    public includeSearch() {}

    public intervalSearch() {}

    public siteSearch(selectValue: any) {
        // const data = [];
        const response = this.publicService.getSelectOptionsList(SELECT_OPTIONS.TSC_DETECTOR);
        const res = response.data;
        if (res && res.length !== 0) {
            this.roadOptions = [...res.filter(item => item.description === selectValue.value)];
            if (this.roadOptions && this.roadOptions.length !== 0) {
                if (localStorage.getItem('itmp_lang') === 'vi') {
                    this.siteOptions.forEach(site => {
                        site.displayName = site.vietName;
                    });
                } else {
                    this.siteOptions.forEach(site => {
                        site.displayName = site.name;
                    });
                }
                this.roadSelect = this.roadOptions[0];
            }
        }
        // if (data && data.length !== 0) {
        //     this.roadOptions = [...data];
        //     this.roadSelect = data[0];
        // }
    }

    // 禁用今天之后的日期选择
    range(start: number, end: number): number[] {
        const result: number[] = [];
        for (let i = start; i < end; i++) {
            result.push(i);
        }
        return result;
    }

    disabledDate = (current: Date): boolean => {
        // Can not select days before today and today
        return differenceInCalendarDays(current, new Date()) > 0;
    };

    disabledDateTime: object = () => {
        return {
            nzDisabledHours: () => this.range(0, 24).splice(4, 20),
            nzDisabledMinutes: () => this.range(30, 60),
            nzDisabledSeconds: () => [55, 56]
        };
    };

    disabledRangeTime: object = (value: Date[], type: 'start' | 'end') => {
        if (type === 'start') {
            return {
                nzDisabledHours: () => this.range(0, 60).splice(4, 20),
                nzDisabledMinutes: () => this.range(30, 60),
                nzDisabledSeconds: () => [55, 56]
            };
        }
        return {
            nzDisabledHours: () => this.range(0, 60).splice(20, 4),
            nzDisabledMinutes: () => this.range(0, 31),
            nzDisabledSeconds: () => [55, 56]
        };
    };
}
